package org.example.elm_springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.elm_springboot.po.Orders;
import org.example.elm_springboot.po.Cart;
import org.example.elm_springboot.po.OrderDetailet;
import org.example.elm_springboot.service.OrdersService;
import org.example.elm_springboot.service.CartService;
import org.example.elm_springboot.service.OrderDetailetService;
import org.example.elm_springboot.service.BusinessService;
import org.example.elm_springboot.service.FoodService;
import java.util.List;
import java.math.BigDecimal;
import org.example.elm_springboot.po.Business;
import org.example.elm_springboot.po.Food;

@RestController
@RequestMapping("/orders")
@CrossOrigin(origins = "http://localhost:5174", allowCredentials = "true")
public class OrdersController {
    
    @Autowired
    private OrdersService ordersService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private OrderDetailetService orderDetailetService;
    
    @Autowired
    private BusinessService businessService;
    
    @Autowired
    private FoodService foodService;
    
    @PostMapping("/createOrders")
    public int createOrders(String userId, Integer businessId, Integer daId, Double orderTotal) {
        try {
            // 获取购物车中的商品
            List<Cart> cartList = cartService.listCart(userId, businessId);
            
            // 获取商家信息（用于获取配送费）
            Business business = businessService.getBusinessById(businessId);
            if (business == null) {
                return 0;
            }
            
            // 计算订单总价
            BigDecimal total = BigDecimal.ZERO;
            for (Cart cart : cartList) {
                // 获取食品信息
                Food food = foodService.getFoodById(cart.getFoodId());
                if (food != null) {
                    // 食品单价 * 数量
                    BigDecimal foodPrice = new BigDecimal(food.getFoodPrice().toString());
                    BigDecimal quantity = new BigDecimal(cart.getQuantity());
                    BigDecimal itemTotal = foodPrice.multiply(quantity);
                    total = total.add(itemTotal);
                }
            }
            
            // 加上配送费
            if (business.getDeliveryPrice() != null) {
                total = total.add(new BigDecimal(business.getDeliveryPrice().toString()));
            }
            
            // 创建订单
            Orders orders = new Orders();
            orders.setUserId(userId);
            orders.setBusinessId(businessId);
            orders.setDaId(daId);
            orders.setOrderTotal(total);
            orders.setOrderDate(String.valueOf(System.currentTimeMillis()));
            orders.setOrderState(0);
            
            // 创建订单并获取订单ID
            int orderId = ordersService.createOrders(orders);
            
            // 如果订单创建成功，继续创建订单明细
            if (orderId > 0) {
                // 创建订单明细
                for (Cart cart : cartList) {
                    OrderDetailet od = new OrderDetailet();
                    od.setOrderId(orders.getOrderId());  // 使用生成的订单ID
                    od.setFoodId(cart.getFoodId());
                    od.setQuantity(cart.getQuantity());
                    orderDetailetService.createOrderDetailet(od);
                }
                
                // 清空购物车
                cartService.removeCart(userId, businessId);
                
                // 返回生成的订单ID
                return orders.getOrderId();  // 返回实际生成的订单ID
            }
            
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    @GetMapping("/getOrdersById")
    public Orders getOrdersById(Integer orderId) {
        return ordersService.getOrdersById(orderId);
    }
    
    @PostMapping("/updateOrderState")
    public int updateOrderState(Integer orderId, Integer orderState) {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setOrderState(orderState);
        return ordersService.updateOrderState(orders);
    }
    
    @GetMapping("/listOrdersByUserId")
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersService.listOrdersByUserId(userId);
    }
    
    @PostMapping("/removeOrder")
    public int removeOrder(Integer orderId) {
        return ordersService.removeOrder(orderId);
    }
    
    @PostMapping("/deleteOrder")
    public int deleteOrder(Integer orderId) {
        return ordersService.deleteOrder(orderId);
    }
} 